// 路由守卫工具
import authManager from './auth.js'

/**
 * 需要登录的页面路径
 */
const LOGIN_REQUIRED_PAGES = [
  '/pages/reserve/reserve',
  '/pages/user/profile',
  '/pages/user/orders',
  '/pages/user/favorites'
]

/**
 * 检查页面是否需要登录
 * @param {string} url - 页面路径
 * @returns {boolean} 是否需要登录
 */
function needLogin(url) {
  return LOGIN_REQUIRED_PAGES.some(page => url.includes(page))
}

/**
 * 路由守卫
 * @param {string} url - 目标页面URL
 * @param {string} type - 跳转类型 (navigateTo, redirectTo, switchTab, reLaunch)
 * @returns {Promise<boolean>} 是否允许跳转
 */
export async function routerGuard(url, type = 'navigateTo') {
  // 初始化认证状态
  const status = authManager.init()
  
  // 检查是否需要登录
  if (needLogin(url) && !status.isLoggedIn) {
    // 需要登录但未登录，跳转到登录页
    const loginUrl = `/pages/login/login?redirect=${encodeURIComponent(url)}`
    
    uni.navigateTo({
      url: loginUrl,
      fail: (error) => {
        console.error('跳转登录页失败:', error)
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
      }
    })
    
    return false
  }
  
  return true
}

/**
 * 安全的页面跳转
 * @param {string} url - 目标页面URL
 * @param {string} type - 跳转类型
 * @param {Object} options - 其他选项
 */
export async function safeNavigate(url, type = 'navigateTo', options = {}) {
  const canNavigate = await routerGuard(url, type)
  
  if (canNavigate) {
    const navigateOptions = {
      url,
      ...options
    }
    
    switch (type) {
      case 'navigateTo':
        uni.navigateTo(navigateOptions)
        break
      case 'redirectTo':
        uni.redirectTo(navigateOptions)
        break
      case 'switchTab':
        uni.switchTab(navigateOptions)
        break
      case 'reLaunch':
        uni.reLaunch(navigateOptions)
        break
      default:
        uni.navigateTo(navigateOptions)
    }
  }
}

/**
 * 检查当前页面是否需要登录
 * @returns {boolean} 是否需要登录
 */
export function checkCurrentPageNeedLogin() {
  const pages = getCurrentPages()
  if (pages.length === 0) return false
  
  const currentPage = pages[pages.length - 1]
  const currentRoute = '/' + currentPage.route
  
  return needLogin(currentRoute)
}

/**
 * 获取当前页面路径
 * @returns {string} 当前页面路径
 */
export function getCurrentPagePath() {
  const pages = getCurrentPages()
  if (pages.length === 0) return ''
  
  const currentPage = pages[pages.length - 1]
  return '/' + currentPage.route
}

/**
 * 检查并跳转到登录页
 * @param {string} redirectUrl - 登录后重定向的URL
 */
export function checkAndGoLogin(redirectUrl = '') {
  const status = authManager.init()
  
  if (!status.isLoggedIn) {
    let loginUrl = '/pages/login/login'
    if (redirectUrl) {
      loginUrl += `?redirect=${encodeURIComponent(redirectUrl)}`
    }
    
    uni.navigateTo({
      url: loginUrl,
      fail: (error) => {
        console.error('跳转登录页失败:', error)
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
      }
    })
    
    return false
  }
  
  return true
} 